/**
 * 
 */
package com.effectivsocial.extension.plugin;

import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;

import lombok.extern.slf4j.Slf4j;

import org.springframework.context.ApplicationContext;

import com.effectivsocial.domain.Company;
import com.effectivsocial.domain.Role;
import com.effectivsocial.domain.User;
import com.effectivsocial.service.api.LovService;
import com.effectivsocial.service.api.UserService;

/**
 * @author Dhrubo
 *
 */
@Named
@Slf4j
public class StartupUserValidatorPlugin implements StartupPlugin {

	@Inject
	private UserService userService;
	
	@Inject
	private LovService lovService;
	
	public void preProcess(ApplicationContext ctx) {
		
		
	}

	private void createAdminUser(Role role) {
		//this is a brand new installation, go ahead and create admin user
        User user = new User();
        user.setFirstName("Admin");
        user.setLastName("Admin");
        user.setEmail("admin@ecrm.com");
        user.setPassword("admin321");
        
        Company company = new Company();
        company.setName("SYSTEM-COMPANY");
        user.setCompany(company);
        
        userService.save(user, role);
        
		
	}

	public void process(ApplicationContext ctx) {
		log.info("Processing startup plugin");
		log.info("Pre processing startup plugin");
		
		Role role = (Role) lovService.findByTypeAndName("Role", "ROLE_ADMIN");
		
		List<User> users = userService.findByRole(role);
		
		if(users != null){
			if(users.size() < 1) {
				//no admin user exists, this is first time load,
				//create a new user with admin role.
				createAdminUser(role);
			}
			else{
				if(log.isInfoEnabled()) {
					log.info("Admin users exist - {}", users.size());
				}
			}
		}
		
	}

	public void postProcess(ApplicationContext ctx) {
		log.info("Post processing startup plugin");
		
	}

	public int getOrder() {
		
		return 400;
	}

	

}
